
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class SessionListen implements HttpSessionListener {

	private int sessionCount;

	public SessionListen() {
		this.sessionCount = 0;
	}

	public void sessionCreated(HttpSessionEvent se) {
		HttpSession session = se.getSession();
		session.setMaxInactiveInterval(60);
		synchronized (this) {
			sessionCount++;
		}
	}

	public void sessionDestroyed(HttpSessionEvent se) {

		HttpSession session = se.getSession();
		String id = session.getId();
		try{
			int gameId = (Integer) session.getAttribute("gameID");

			ArrayList<Game> gamesArray = GamesHandler.games;
			for (int i = 0; i < gamesArray.size(); i++) {
				if (gamesArray.get(i).getId() == gameId) {
					GamesHandler.games.remove(gamesArray.get(i));
					break;
				}
			}
		}catch (Exception e) {
			// TODO: handle exception
		}

		synchronized (this) {
			--sessionCount;
		}
		
		if(sessionCount==0){
			ArrayList<Game> gamesArray = GamesHandler.games;
			for (int i = 0; i < gamesArray.size(); i++) {
				GamesHandler.games.remove(gamesArray.get(i));
				try {
					finalize();
				} catch (Throwable e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	
	}
}


